import 'package:beamer/beamer.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:rabbit_mobile/i18n/strings.g.dart';
import 'package:rabbit_mobile/provide/riverpod_provider.dart';
import 'package:rabbit_mobile/source/language_constant.dart';
import 'package:rabbit_mobile/view/Category/models/category_model.dart';
import 'package:rabbit_mobile/widget/custom_cache_image_widget/index.dart';
import 'package:rabbit_mobile/widget/price_Widget/index.dart';

class Category extends ConsumerStatefulWidget {
  const Category({super.key});

  @override
  _CategoryState createState() => _CategoryState();
}

class _CategoryState extends ConsumerState<Category> with AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => true;
  late var _categoryLevelIndex = 0;

  // 居中的控制器
  late ScrollController _scrollController;

  /// 一級分類試圖的key: 用來獲取一級分類試圖的寬高(組件的基本信息)
  final GlobalKey _primaryCategoryGlobelKey = GlobalKey(debugLabel: "_primaryCategoryGlobelKey");

  @override
  void initState() {
    super.initState();
    _scrollController = ScrollController();
    // Future.microtask(() => ref.read(categoryProvider.notifier).fetchCategories());
  }

  @override
  void dispose() {
    super.dispose();
    _scrollController.dispose();
  }

  // 分類點擊事件
  void _primaryLevelOnTap(int index, int length, String id) {
    if (_categoryLevelIndex == index) return;
    // 獲取選中的一級分類的中心點: (index + 0.5) * 高度
    double selectPoint = (index + 0.5) * 60;
    // 獲取一級分類滾動試圖高度的一半: GLobalKey
    RenderBox box = _primaryCategoryGlobelKey.currentContext?.findRenderObject() as RenderBox;
    double categoryBoxHeight = box.size.height;
    // 計算居中的位置
    double centerOffset = selectPoint - categoryBoxHeight * 0.5;
    // 最小滾動距離
    double minOffset = 0.0;
    // 最大滾動距離
    double maxOffset = length * 60 - categoryBoxHeight;
    if (centerOffset <= minOffset) {
      centerOffset = minOffset;
    } else if (centerOffset >= maxOffset) {
      centerOffset = maxOffset;
    }
    ref.watch(categorySecondsProvide(id));
    _scrollController.animateTo(centerOffset,
        duration: const Duration(milliseconds: 400), curve: Curves.ease);
    setState(() {
      _categoryLevelIndex = index;
    });
  }

  /// 一級分類的構建函數
  Widget _firstLevelCategoryBuildWidget(AsyncValue<CategoryFirstLevel> categoryState) {
    return Expanded(
      flex: 1,
      child: SizedBox(
        child: Builder(
          builder: (context) {
            if (categoryState.isLoading) {
              // 加载中
              return const Center(
                child: CircularProgressIndicator(),
              );
            } else if (categoryState.value != null && categoryState.value!.result.isNotEmpty) {
              // 数据加载成功
              final categoryFirstLevelData = categoryState.value!;
              return ListView.builder(
                key: _primaryCategoryGlobelKey,
                controller: _scrollController,
                itemCount: categoryFirstLevelData.result.length,
                itemBuilder: (context, index) {
                  return GestureDetector(
                    onTap: () => _primaryLevelOnTap(index, categoryFirstLevelData.result.length,
                        categoryFirstLevelData.result[index].id),
                    child: Container(
                      decoration: BoxDecoration(
                        color: _categoryLevelIndex == index
                            ? Colors.white
                            : const Color.fromARGB(255, 250, 237, 252),
                      ),
                      height: 60,
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceAround,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          Container(
                            width: 4,
                            height: 46,
                            decoration: BoxDecoration(
                              color:
                                  _categoryLevelIndex == index ? Colors.teal : Colors.transparent,
                            ),
                          ),
                          Expanded(
                            flex: 1,
                            child: Text(
                              homePageLanguage(categoryFirstLevelData.result[index].name),
                              style: TextStyle(
                                  fontSize: 14,
                                  color: _categoryLevelIndex == index
                                      ? const Color.fromARGB(255, 82, 82, 82)
                                      : Colors.grey.shade600,
                                  fontWeight: _categoryLevelIndex == index
                                      ? FontWeight.bold
                                      : FontWeight.normal),
                              textAlign: TextAlign.center,
                            ),
                          ),
                        ],
                      ),
                    ),
                  );
                },
              );
            } else if (categoryState.hasError) {
              // 加载失败
              return const Center(
                child: Text("加载失败"),
              );
            } else {
              // 没有数据
              return const Center(
                child: Text("没有分类数据"),
              );
            }
          },
        ),
      ),
    );
  }

  /// 二級分類的構建函數
  Widget _secondsLevelCategoryBuildWidget(
      AsyncValue<CategorySecondsLevel?> categorySecondData, double imgWidth) {
    return Expanded(
      flex: 3,
      child: Container(
        padding: const EdgeInsets.only(top: 10, right: 10, left: 10),
        decoration: const BoxDecoration(color: Colors.white),
        child: Builder(
          builder: (context) {
            if (categorySecondData.isLoading) {
              return Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Image.asset(
                      'assets/loading.gif',
                      width: 100,
                      height: 100,
                    ),
                    Text(t.loading),
                  ],
                ),
              );
            } else if (categorySecondData.value != null &&
                categorySecondData.value!.children.isNotEmpty) {
              final item = categorySecondData.value!.children;
              return ListView.builder(
                itemCount: categorySecondData.value!.children.length,
                itemBuilder: (context, index) {
                  return Column(
                    children: [
                      Padding(
                        padding: EdgeInsets.only(bottom: 12, top: index != 0 ? 32 : 0),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            Text(
                              item[index].name,
                              style: const TextStyle(
                                fontSize: 16,
                                color: Colors.grey,
                              ),
                            ),
                            Text(
                              "${t.more} >>",
                              style: const TextStyle(
                                fontSize: 14,
                                color: Colors.grey,
                              ),
                            )
                          ],
                        ),
                      ),
                      AlignedGridView.count(
                        crossAxisCount: 3,
                        mainAxisSpacing: 10,
                        crossAxisSpacing: 10,
                        itemCount: item[index].goods.length,
                        shrinkWrap: true,
                        physics: const NeverScrollableScrollPhysics(),
                        itemBuilder: (context, index2) {
                          final goodsItem = item[index].goods;
                          return Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              GestureDetector(
                                onTap: () {
                                  Beamer.of(context)
                                      .beamToNamed('/goodsDetails/${goodsItem[index2].id}');
                                },
                                child: CustomCacheImageWidget(
                                  imageUrl: goodsItem[index2].picture,
                                  width: imgWidth,
                                  height: imgWidth,
                                ),
                              ),
                              Text(
                                goodsItem[index2].name,
                                style: const TextStyle(
                                  fontSize: 12,
                                  color: Colors.grey,
                                ),
                                maxLines: 2,
                                overflow: TextOverflow.ellipsis,
                              ),
                              PriceWidget(price: goodsItem[index2].price)
                            ],
                          );
                        },
                      ),
                    ],
                  );
                },
              );
            } else if (categorySecondData.hasError) {
              return const Center(
                child: Text("數據錯誤"),
              );
            } else {
              return const Center(
                child: Text("沒有數據"),
              );
            }
          },
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);

    /// 一級分類數據
    final categoryState = ref.watch(categoryProvider);
    final String? currentCategoryId = categoryState.value?.result.isNotEmpty == true
        ? categoryState.value?.result[_categoryLevelIndex].id
        : null;

    /// 二級分類數據
    final categorySecondData = currentCategoryId != null
        ? ref.watch(categorySecondsProvide(currentCategoryId))
        : const AsyncValue.data(null);

    /// 圖片寬度
    double imgWidth = (MediaQuery.of(context).size.width * 0.75 - 40) / 3;

    return Scaffold(
      appBar: const CateAppBar(),
      body: Padding(
        padding: const EdgeInsets.only(top: 10),
        child: Row(
          children: [
            _firstLevelCategoryBuildWidget(categoryState),
            _secondsLevelCategoryBuildWidget(categorySecondData, imgWidth)
          ],
        ),
      ),
    );
  }
}

class CateAppBar extends StatelessWidget implements PreferredSizeWidget {
  const CateAppBar({super.key});

  @override
  Size get preferredSize => const Size(double.infinity, kToolbarHeight);

  @override
  Widget build(BuildContext context) {
    return Container(
      height: MediaQuery.of(context).padding.top + kTextTabBarHeight,
      decoration: const BoxDecoration(
        image: DecorationImage(
          image: AssetImage("assets/home_appBar_bg.png"),
          fit: BoxFit.cover,
        ),
      ),
      child: SafeArea(
        child: Center(
          child: Text(
            t.categories,
            style: const TextStyle(fontSize: 16.0, color: Colors.white),
          ),
        ),
      ),
    );
  }
}
